/* -----------------------------------------------------------------------------
 * PROJECT    : lwf
 * FILE       : StaticWorkSheetAction.java
 *
 * HISTORY:
 * Date          Author                        Description
 * ----------------------------------------------------------------------------- 
 * Mar 22, 2011  mycodetalks			       Created
 */
package net.lwf.web.struts.action.worksheet;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lwf.handler.IProcessHandler;
import net.lwf.common.constant.ICommonConstant;
import net.lwf.constant.IDalConstant;
import net.lwf.exception.ExceptionUtil;
import net.lwf.factory.lookup.LookupFactory;
import net.lwf.file.util.FileReader;
import net.lwf.jaxb.entity.StaticWorkSheet;
import net.lwf.jaxb.service.maths.worksheet.StaticWorkSheetService;
import net.lwf.lookup.fake.service.MockLookupService;
import net.lwf.security.DesEncryptor;
import net.lwf.service.LookupService;
import net.lwf.service.LwfService;
import net.lwf.web.constant.IPageTitle;
import net.lwf.web.servlet.pdf.PdfProcessingServlet;
import net.lwf.web.struts.action.LwfWorksheetAction;
import net.lwf.web.struts.action.LwfWorksheetActionForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * This class will be retired soon.
 */
public class StaticWorkSheetAction extends LwfWorksheetAction {
	
	private String subject;
	//rename to statichome
/*	public ActionForward wshome(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//Get subject, topic names from the request
		String subject = request.getParameter("subject");
		String topic = request.getParameter("topic");
		
		StaticWorksheetActionForm swaform = (StaticWorksheetActionForm) form;
		swaform.setSubject(subject);
		swaform.setTopic(topic);
		
		StaticWorkSheetService service = new StaticWorkSheetService();
		List<StaticWorkSheet> worksheets = service.getUniqueWorkSheets(getGrade(), subject, topic);
		this.setPrintKey(worksheets);
		
		swaform.setWorksheets(worksheets);
		
		return mapping.findForward("wshome");
	}*/
	
	public ActionForward wshome(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//Get subject, topic names from the request
		//String subject = request.getParameter("subject");
		this.subject = request.getParameter("subject");
		String topic = request.getParameter("topic");
		
		LwfWorksheetActionForm baseform = (LwfWorksheetActionForm) form;
		baseform.resetWsInfo();
		baseform.setSubject(subject);
		baseform.setTopic(topic);
		
		StaticWorkSheetService service = new StaticWorkSheetService();
		List<StaticWorkSheet> worksheets = service.getUniqueWorkSheets(getGrade(), subject.toLowerCase(), topic.toLowerCase());
		this.setPrintKey(worksheets);
		
		baseform.setWorksheets(worksheets);
		
		return mapping.findForward("wshome");
	}
	
	public ActionForward swsdisplay(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
	   	String[] baseInfo = this.getPrintFile(request);
    	//String wsId = baseInfo[0];
    	String filepath = baseInfo[1];
    	//String baseFolder = LookupFactory.getInstance().getValue(IDalConstant.PDF, IDalConstant.PDF_BASE_FOLDER_KEY);
    	String baseFolder = new LookupService().getValue(IDalConstant.PDF, IDalConstant.PDF_BASE_FOLDER_KEY);
    	
    	//long id = Long.parseLong(wsId);
    	//User user = (User) getUser(request).getUser();

		//Verify whether the file is printed/accessed by the logged in user in the current day
		//WorkSheetManager manager = new WorkSheetManager();
		//boolean wsaccessed = manager.workSheetAccessed(user.getId(), this.formatWsAccessKey(filepath));
		
		//if(!wsaccessed || (wsaccessed && !manager.workSheetHasRestrictions(id))) {
		    String contentType = getServlet().getServletContext().getMimeType(filepath);
	    	response.setContentType(contentType);
			//New
	    	response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");
			
	        OutputStream out = response.getOutputStream();
	        byte[] pdfContent = FileReader.loadFile(baseFolder + filepath);
	        out.write(pdfContent, 0, pdfContent.length); //This should be same as out.write(b);
	        if (out != null) {
	            out.close();
	        }
	        //Log the entry
	       // manager.logWorkSheetAccess(user.getId(), id, this.formatWsAccessKey(filepath));
		//}
		//else {
		//	return mapping.findForward("printerror");
		//}
		
		return null;
	}

	@Override
	public IProcessHandler getHandler(HttpServletRequest request) {
		return null;
	}
	
	public void setPrintKey(List<StaticWorkSheet> worksheets) {
		String encryptionKey = null;
		String encryptionScheme = null;

		if(LwfService.isMock()) {
			MockLookupService service = new MockLookupService();
			encryptionKey = service.getLookupValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_KEY);
			encryptionScheme = service.getLookupValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_SCHEME_KEY);
		}
		else {
			encryptionKey = LookupFactory.getInstance().getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_KEY);
			encryptionScheme = LookupFactory.getInstance().getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_SCHEME_KEY);
		}
		DesEncryptor encryptor = null;
		try {
			try {
				encryptor = new DesEncryptor(encryptionScheme, encryptionKey);
			}
			catch(Exception ex) {
				System.err.println(ex.getMessage());
				ex.printStackTrace();
			}
			
			for(StaticWorkSheet worksheet: worksheets) {
				//Encrypt print key
				String key_to_encrypt = worksheet.getPrintKey();
	
				String encrypted = encryptor.encrypt(key_to_encrypt);
				String encoded = URLEncoder.encode(encrypted, ICommonConstant.CHARACTER_ENCODING);
				worksheet.setEncryptedPrintKey(encoded);
			}
		} 
		catch (UnsupportedEncodingException useex) {
			ExceptionUtil.logAndThrowException("Could not encrypt the data......", StaticWorkSheetAction.class, useex);
		}
	}
	
    private String[] getPrintFile(HttpServletRequest request) {
    	String[] data = new String[2];  //first element is wsId and second element is filepath
		String printKey = request.getParameter("key");

		if(printKey != null) {
			//decode the key first
			String decodedPrintKey = null;
			try {
				decodedPrintKey = URLDecoder.decode(printKey, ICommonConstant.CHARACTER_ENCODING);
			} catch (UnsupportedEncodingException useex) {
				ExceptionUtil.logAndThrowException(PdfProcessingServlet.class, useex);
			}
			decodedPrintKey = decodedPrintKey.replace(ICommonConstant.SPACE, ICommonConstant.PLUS);
			//decrypt key
//			String encryptionKey = LookupFactory.getInstance().getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_KEY);
//			String encryptionScheme = LookupFactory.getInstance().getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_SCHEME_KEY);
			LookupService service = new LookupService();
			String encryptionKey = service.getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_KEY);
			String encryptionScheme = service.getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_SCHEME_KEY);
			DesEncryptor encryptor = new DesEncryptor(encryptionScheme, encryptionKey);
			String decrypted = encryptor.decrypt(decodedPrintKey);
			StringTokenizer stk = new StringTokenizer(decrypted, ICommonConstant.PIPE);
			String wsId = stk.nextToken();
			String filepath = stk.nextToken();

			data[0] = wsId;
			data[1] = filepath;

		}
		else {
			//No print key
		}
		return data;
    }

	@Override
	public String getPdfLink() {
		return null;
	}

	@Override
	public String getQuizLink() {
		return null;
	}

	@Override
	public String getPageTitle() {
		return IPageTitle.WORKSHEETS;
	}

	@Override
	public String getMainTitle() {
		return this.subject + " - " + getOperation();
	}

}



